package com.lsx143.wordcount.day6;

import com.lsx143.wordcount.bean.WaterSensor;
import com.lsx143.wordcount.util.MyUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Flink_ListState {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env.socketTextStream("hadoop162", 9999)
                .flatMap(new FlatMapFunction<String, WaterSensor>() {
                    @Override
                    public void flatMap(String line, Collector<WaterSensor> out) throws Exception {
                        String[] datas = line.split(",");
                        out.collect(new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2])));
                    }
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private ListState<Integer> waters;
                    private List<Integer> waterList = new ArrayList<>();

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        waters = getRuntimeContext().getListState(new ListStateDescriptor<>("waterTop3", Integer.class));
                        System.out.println("init-ListState");
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        Integer currentVC = value.getVc();
                        waters.add(currentVC);
                        waterList = MyUtil.toList(waters.get());
                        waterList.sort((o1, o2) -> o2.compareTo(o1));
                        if (waterList.size() == 4) {
                            waterList.remove(waterList.size() - 1);
                        }
                        waters.update(waterList);
                        out.collect(waterList.toString());
                    }
                })
                .print();
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}